package com.quanyan.club.task.tracker;

import com.alibaba.fastjson.JSONObject;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.club.entity.db.TbClubActivityExample;
import com.quanyan.club.mapper.ClubActivityCRUDMapper;
import com.quanyan.club.service.ActivityCRUDService;
import com.quanyan.common.utils.Limit;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by yue.yuan on 2016/12/14.
 */
@Component
public class ActivityCreateCycleRangeJob implements JobRunner{

    private static Logger logger = Logger.getLogger(ActivityCreateCycleRangeJob.class);

    @Autowired
    private ClubActivityCRUDMapper clubActivityCRUDMapper;
    @Autowired
    private ActivityCRUDService activityCRUDService;

    @Override
    public Result run(JobContext jobContext) throws Throwable {
        createCycleRangeActivity();
        return new Result(Action.EXECUTE_SUCCESS);//createWeekRangeActivity();
    }

    //@Async
    public void createCycleRangeActivity()
    {
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        TbClubActivityExample.Criteria clubCriteria = clubActivityExample.createCriteria();
        //48小时内创建并已经结束的,没被删除,未被取消,且是周期,且有日循环,且未扫描过的周期性俱乐部活动
        Map<String, Object> map = new HashMap<String, Object>();
        Calendar calendar = Calendar.getInstance(Locale.CHINESE);
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_WEEK, -10);//一周以内
        map.put("createTime", calendar.getTime());
        int total = clubActivityCRUDMapper.countCycleRangeActivity(map);
        if(0 == total)
        {
            logger.warn("没有未扫描的日循环活动");
            return;
        }
        Integer pageSize = 20;
        for (int i = 0; i < Math.ceil((double)total/pageSize); i++) {

            int pageNum = i + 1;
            Limit limit = Limit.buildLimit(pageNum, pageSize);
            map.put("pageStart", limit.getStart());
            map.put("pageSize", limit.getSize());

            List<Integer> rootIds = clubActivityCRUDMapper.selectCycleRangeActivity(map);
            logger.warn("活动模块返回日循环活动可更新量：" + JSONObject.toJSONString(rootIds));
            if(null == rootIds || rootIds.size() == 0)
            {
                continue;
            }
            Map<Integer, Integer> idMaps = activityCRUDService.createActivityFromExist(rootIds);
            logger.warn("更新日循环批次结束，新旧ID：" + JSONObject.toJSONString(idMaps));
        }

    }

}
